package com.dz.lm.common.util;

import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.random.RandomUtils;
import org.apache.commons.lang.StringUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ImagesUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
    private static InputStream in;
    private static Properties p;
    private static String dev_path = "";
    private static String test_path = "";
    private static String prod_path = "";
    private static String test_Ip = "";
    private static String realm_name = "www.sankedouzi.com";
    private static String realm_name_cn = "www.sankedouzi.cn";
    private static String separator = "/";
    static {
        try {
            in = FileUploadUtil.class.getClassLoader().getResourceAsStream("upload.properties");
            p = new Properties();
            p.load(in);
            dev_path = p.getProperty("dev_upload_path");
            test_path = p.getProperty("test_upload_path");
            prod_path = p.getProperty("prod_upload_path");
            test_Ip = p.getProperty("test_Ip");
        } catch (FileNotFoundException e) {
            logger.error("upload Not Found File :upload.properties");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("upload IOException");
            e.printStackTrace();
        }
    }

    /*public static void getVideoPic(File video, String picPath) {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        try {
            ff.start();
            // 截取中间帧图片(具体依实际情况而定)
            int i = 0;
            int length = ff.getLengthInFrames();
            int middleFrame = length / 2;
            org.bytedeco.javacv.Frame frame = null;
            while (i < length) {
                frame = ff.grabFrame();
                if ((i > middleFrame) && (frame.image != null)) {
                    break;
                }
                i++;
            }
            // 截取的帧图片
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage srcImage = converter.getBufferedImage(frame);
            int srcImageWidth = srcImage.getWidth();
            int srcImageHeight = srcImage.getHeight();
            // 对截图进行等比例缩放(缩略图)
            int width = 480;
            int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
            BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File picFile = new File(picPath);
            ImageIO.write(thumbnailImage, "jpg", picFile);
            ff.stop();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static long getVideoDuration(File video) {
        long duration = 0L;
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        try {
            ff.start();
            duration = ff.getLengthInTime() / (1000 * 1000);
            ff.stop();
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
        return duration;
    }*/
    public static Map<String, Object> getScreenshot(String filePath) throws Exception{

        System.out.println("截取视频截图开始："+ System.currentTimeMillis());
        Map<String, Object> result = new HashMap<String, Object>();
        FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);
        String path = "";
        String suffixName = "jpg";
        String fileName = MD5Util.MD5(RandomUtils.generateString(16));
        String subPath = separator + "video" + separator + DateUtil.dateToYYYYMMDD(new Date()) ;
        fileName = fileName + "." + suffixName;
        if (test_path == null || "".equals(test_path)) {
            path = prod_path;
        } else {
            path = test_path;
        }
        grabber.start();
        //设置视频截取帧（默认取第一帧）
        org.bytedeco.javacv.Frame frame = grabber.grabImage();
        //视频旋转度
        String rotate = grabber.getVideoMetadata("rotate");
        Java2DFrameConverter converter = new Java2DFrameConverter();
        //绘制图片
        BufferedImage bi = converter.getBufferedImage(frame);
        if (rotate != null) {
            // 旋转图片
            bi = rotate(bi, Integer.parseInt(rotate));
        }
        //图片的类型
        String imageMat = "jpg";
        //图片的完整路径
        String imagePath = path + subPath +separator+ fileName;
        //创建文件
        File file=new File(path+subPath);
        if(!file.exists()){//如果文件夹不存在
            boolean mkdir = file.mkdirs();//创建文件夹
        }
        File output = new File(imagePath);


        ImageIO.write(bi, imageMat, output);
        result.put("key", "/img" + subPath +separator+ fileName);
        return result;
    }

    /**
     * @Description: 根据视频旋转度来调整图片
     * @param src
     * @param angel	视频旋转度
     * @return  BufferedImage
     */
    public static BufferedImage rotate(BufferedImage src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        int type = src.getColorModel().getTransparency();
        Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
        BufferedImage bi = new BufferedImage(rect_des.width, rect_des.height, type);
        Graphics2D g2 = bi.createGraphics();
        g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return bi;
    }


    /**
     * @Description: 计算图片旋转大小
     * @param src
     * @param angel
     * @return  Rectangle
     */
    public static Rectangle calcRotatedSize(Rectangle src, int angel) {
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new java.awt.Rectangle(new Dimension(des_width, des_height));
    }

}
